<template>
  <div id="AreaTree">
    <el-autocomplete
      popper-class="my-autocomplete"
      v-model="state"
      :fetch-suggestions="fetchData"
      placeholder="请输入内容"
      @select="handleSelect"
    >
      <el-button slot="append" icon="el-icon-search"></el-button>
      <template>
        <el-tree
          ref="areaTree"
          :data="regArr"
          :props="props"
          :load="loadNode"
          @node-click="handleNodeClick"
          node-key="code"
          lazy
        ></el-tree>
      </template>
    </el-autocomplete>
  </div>
</template>

<script>
export default {
  name:'AreaTree',
  data(){
    return{
      // 定义树的结构
      props: {
        label: 'name',
        children: 'hasChildren',
        isLeaf: 'leaf'
      },
    }
  },
  created(){
    this.fetchData()
  },
  methods: {
    fetchData(){
      this.$get("/area/2/child").then(r => {
        this.regArr = r.data.data;
      })
    },
    //获取节点数据
    loadNode(node, resolve) {
      var areaId = node.data.areaId;
      if(node.data.hasChildren){
        this.$get("/area/"+areaId+"/child/").then(r => {
          var data = r.data.data;
          data.forEach(i=>{
            if(!i.hasChildren){
              i.leaf = true;
            }
          })
          resolve(r.data.data);
        })
      }else{
        return resolve([]);
      }
    },

    //获取选中的数据
    handleNodeClick(data) {
      if(!data.hasChildren){
        this.isshow = false;
        this.textVal = data.fullName;
        this.$emit("regArr", data)
      }else{
        this.propsData = data;
      }
    }
  }

}
</script>

<style>
</style>
